package cn.iocoder.yudao.module.contract.utils;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.module.infra.api.file.FileApi;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.jsoup.Jsoup;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class HtmlToFileConverter {
    @Resource
    private FileApi fileApi;

    /**
     * 替换html变量
     * @param htmlContent
     * @param map
     * @return
     * @throws IOException
     * @throws TemplateException
     */
    public static String authHtmlToPdf(String htmlContent,  Map<String, Object> map) throws Exception{
        StringWriter stringWriter = new StringWriter();
        Template template = null;
        template = new Template("SysMessageTemplate", htmlContent,null);
        template.process(map, stringWriter);
        htmlContent = stringWriter.toString();
        return htmlContent;
    }

    /**
     * html转doc
     *
     * @param htmlContent
     * @param keyWord
     */
    public String htmlToWord(String htmlContent,String path,String keyWord){
        // 组装html（替换为自己的html）
        if (StringUtils.isNotEmpty(htmlContent)) {
            // 上传文件路径
//            String filePath = RuoYiConfig.getUploadPath();
//            String fileName = FileUploadUtils.extractFilename(keyWord,"doc");
//            String absPath = FileUploadUtils.getAbsoluteFile(filePath, fileName).getAbsolutePath();
            // 生成临时文件（doc）
            try {
                File file = File.createTempFile(keyWord,".doc");
                // 生成doc格式的word文档，需要手动改为docx
                byte by[] = htmlContent.getBytes("UTF-8");
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(by);
                POIFSFileSystem poifsFileSystem = new POIFSFileSystem();
                DirectoryEntry directoryEntry = poifsFileSystem.getRoot();
                directoryEntry.createDocument("WordDocument", byteArrayInputStream);
                // 文件路径
                // 保存doc文档
                FileOutputStream outputStream = new FileOutputStream(file.getPath());
                poifsFileSystem.writeFilesystem(outputStream);
                byteArrayInputStream.close();
                outputStream.close();
                return fileApi.createFile(keyWord+".doc",path+"/"+file.getName(),getFileBytes(file.getPath()));

//                return FileUploadUtils.getPathFileName(filePath, fileName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * html转doc
     *
     * @param htmlContents
     * @param keyWord
     */
    public String htmlToWord(List<String> htmlContents, String path, String keyWord){
        // 组装html（替换为自己的html）
        String htmlContent = StrUtil.join("", htmlContents);
        htmlContent = Jsoup.parse(htmlContent).html();
        if (StringUtils.isNotEmpty(htmlContent)) {
            // 生成临时文件（doc）
            try {
                File file = File.createTempFile(keyWord,".doc");
                // 生成doc格式的word文档，需要手动改为docx
                byte by[] = htmlContent.getBytes("UTF-8");
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(by);
                POIFSFileSystem poifsFileSystem = new POIFSFileSystem();
                DirectoryEntry directoryEntry = poifsFileSystem.getRoot();
                directoryEntry.createDocument("WordDocument", byteArrayInputStream);
                // 文件路径
                // 保存doc文档
                FileOutputStream outputStream = new FileOutputStream(file.getPath());
                poifsFileSystem.writeFilesystem(outputStream);
                byteArrayInputStream.close();
                outputStream.close();

                return fileApi.createFile(keyWord+".doc",path+"/"+file.getName(),getFileBytes(file.getPath()));
//                return FileUploadUtils.getPathFileName(filePath, fileName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
//    public static void main(String[] args) {
//        List<String> htmlContents = new ArrayList<>();
//        htmlContents.add("<html><body><h1>First Page</h1><p>This is the content of the first page.</p></body></html>");
//        htmlContents.add("<html><body><h1>Second Page</h1><p>This is the content of the second page.</p></body></html>");
//        htmlToWord(htmlContents,"","123123");
//    }

    /**
     * html转pdf
     *
     * @param htmlStr
     * @param keyWord
     * @throws Exception
     */
    public String htmlToPdf(String htmlStr,String keyWord) throws Exception {
        htmlStr = htmlStr.replaceAll("border: none;","border-left: none;border-right: none;border-top: none;border-bottom: none;");
        File file = File.createTempFile(keyWord,".pdf");
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, Files.newOutputStream(file.toPath()));
        document.open();
        XMLWorkerFontProvider fontImp = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
//        fontImp.register("C:\\Windows\\Fonts\\simsun.ttc");
        fontImp.registerDirectory("C:\\Windows\\Fonts");
        XMLWorkerHelper.getInstance().parseXHtml(writer, document, IoUtil.toUtf8Stream(htmlStr), StandardCharsets.UTF_8, fontImp);
        document.close();

        return fileApi.createFile(keyWord+".pdf",null,getFileBytes(file.getPath()));
    }
//    public String htmlToPng(String htmlStr,String keyWord) throws Exception {
//        File file = File.createTempFile(keyWord,"png");
//        HtmlParser htmlParser = new HtmlParserImpl();
//        htmlParser.loadHtml(htmlStr);
//        ImageRenderer imageRenderer = new ImageRendererImpl(htmlParser);
//        imageRenderer.setWidth(955);
//        imageRenderer.saveImage(file.getPath());
//        return fileApi.createFile(keyWord+".png",null,getFileBytes(file.getPath()));
//    }

    public static byte[] getFileBytes(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        return Files.readAllBytes(path);
    }

}